<?php

namespace App\Listeners;


use App\Events\Event;
use App\Events\AppointEvent;
use App\Model\Business\ClasseStuden;
use App\Model\Business\Schedule;
use App\Model\Foundation\Student;
use Illuminate\Support\Facades\DB;


class AppiontListener extends  Listener
{
    /**
     * @param AppointEvent $event
     */
    public function handle(AppointEvent $event)
    {
        switch($event->action)
        {
            case Event::CREATE:
                if(env('ASYN_MODE')){
                    break;
                }
                $this->create($event);
                $this->student($event);
                break;
            case Event::UPDATE:
                if($event->courseId){
                    $this->update($event);
                    $this->student($event);
                }
                break;
            case Event::DELETE:
                if($event->courseId){
                    $this->delete($event);
                }
                break;
            case Event::STUDENT:
                if($event->courseId){
                    $this->student($event);
                }else{
                    $this->syncdata($event);
                }
                break;
            default: break;
        }
    }

    /**
     * 创建课程
     * @param AppointEvent $event
     * @throws \Exception
     */

    function create(AppointEvent $event)
    {
        try{
            $this->setUri('addCourse');
            $cfile = $this->uploadCheck($event->Filedata);
            $data = $this->dataMaker();
            $data["courseName"] = $event->courseName;
            $data["folderId"] = $event->folderId;
            $data["Filedata"] = $cfile;
            $data["expiryTime"] = $event->expiryTime;
            $this->setRequest($data);
            $result = $this->callEeoApi();
            if($result['error_info']['errno'] === 1) {
                $event->setCourseID($result['data']);
                $schduleEvents = $event->getLessons();
                foreach($schduleEvents as $scheduleEvent) {
                    $scheduleEvent->setCourseID($result['data']);
                    event($scheduleEvent);
                }
            }else{
                throw new \Exception($result['error_info']['error'], $result['error_info']['errno']);
            }
        }catch (\Exception $e){
            throw $e;
        }
    }

    /**
     * 更新课程
     * @param AppointEvent $event
     */
    function update(AppointEvent $event)
    {
        try{
            $this->setUri('editCourse');
            $data = $this->dataMaker();
            $data["courseId"] = $event->courseId;
            $data["folderId"] = $event->folderId;
            $data["courseName"] = $event->courseName;
            $data["expiryTime"] = $event->expiryTime;
            $this->setRequest($data);
            $result = $this->callEeoApi();

            if($result['error_info']['errno'] === 1) {
                $schduleEvents = $event->getLessons();
                foreach($schduleEvents as $scheduleEvent) {
                    event($scheduleEvent);
                }
            }else{
                throw new \Exception($result['error_info']['error'], $result['error_info']['errno']);
            }
        }catch (\Exception $e){
            throw $e;
        }
    }

    /**
     * 删除课程
     * @param AppointEvent $event
     */
    function delete(AppointEvent $event)
    {
        try{
            if($event->courseId){
                $this->setUri('delCourse');
                $data = $this->dataMaker();
                $data["courseId"] = $event->courseId;
                $this->setRequest($data);
                $result = $this->callEeoApi();
		if ($result['error_info']['errno'] == 1) {
                    $event->delCourseID();
                } else {
                    throw new \Exception($result['error_info']['error'], $result['error_info']['errno']);
                }
            }
        }catch (\Exception $e){
            throw $e;
        }
    }

    /**
     * 课程下添加/删除学生
     * @param $event
     */
    protected function student(AppointEvent $event)
    {
        try{
            $olds = $event->getStudents(true);
            $news = $event->getStudents();
            $data = $this->dataMaker();
            $data["courseId"] = $event->courseId;
            if(!empty($olds)){
                $this->delstudents($event,$olds);
            }

            if(!empty($news)){
                $this->addstudents($event,$news);
            }
        }catch (\Exception $e){
            throw $e;
        }
    }

    /**
     * 课程下删除学生
     * @param $event
     * @param $olds
     * @throws \Exception
     *
     */

    protected function delstudents($event,$olds)
    {
        $myOlds=[];
        $data = $this->dataMaker();
        $data["courseId"] = $event->courseId;
        $this->setUri('delCourseStudentMultiple');
        foreach ($olds as $old) {
            $myOlds[] = $old['studentAccount'];
        }
        $data['studentJson'] = json_encode($myOlds);
        $data["identity"] = $event->identity;
        $this->setRequest($data);
        $result = $this->callEeoApi();
        $code = $result['error_info']['errno'];
        if (in_array($code, [1])) {
            foreach ($result['data'] as $key => $res) {
                if (!in_array($res['errno'], [1])) {
                    $msg = '学生：'.$myOlds[$key].$res['error'];
                    $data = $this->dataMaker();
                    $data["courseId"] = $event->courseId;
                    $myNews = [];
                    $org = Event::getOrg();
                    $this->setUri('addCourseStudentMultiple');
                    foreach ($olds as $new) {
                        $myNew = [];
                        $myNew['account'] = $new['studentAccount'];
                        $myNew['name'] = $new['studentName'];
                        $myNew['password'] = $org['registerDefaultPwd'];
                        $myNews[] = $myNew;
                    }
                    $data['studentJson'] = json_encode($myNews);
                    $data["isRegister"] = 1;
                    $data["identity"] = $event->identity;
                    $this->setRequest($data);
                    $result = $this->callEeoApi();
                    throw new \Exception($msg, $res['errno']);
                }
            }
        } else {
            throw new \Exception($result['error_info']['error'], $result['error_info']['errno']);
        }
    }

    /**
     * 课程下添加学生
     * @param $event
     * @param $olds
     * @throws \Exception
     *
     */

    protected function addstudents($event,$news)
    {
        $data = $this->dataMaker();
        $data["courseId"] = $event->courseId;
        $myNews = [];
        $org = Event::getOrg();
        $this->setUri('addCourseStudentMultiple');
        foreach ($news as $new) {
            $myNew = [];
            $myNew['account'] = $new['studentAccount'];
            $myNew['name'] = $new['studentName'];
            $myNew['password'] = $org['registerDefaultPwd'];
            $myNews[] = $myNew;
        }
        $data['studentJson'] = json_encode($myNews);
        $data["isRegister"] = 1;
        $data["identity"] = $event->identity;
        $this->setRequest($data);
        $result = $this->callEeoApi();
        $code = $result['error_info']['errno'];
        if (in_array($code, [1])) {
            foreach ($result['data'] as $key => $res) {
                if (!in_array($res['errno'], [1])) {
                    $msg = '学生：'.$myNews[$key]['name'].$myNews[$key]['account'].$res['error'];
                    $myOlds=[];
                    $data = $this->dataMaker();
                    $data["courseId"] = $event->courseId;
                    $this->setUri('delCourseStudentMultiple');
                    foreach ($news as $old) {
                        $myOlds[] = $old['studentAccount'];
                    }
                    $data['studentJson'] = json_encode($myOlds);
                    $data["identity"] = $event->identity;
                    $this->setRequest($data);
                    $result = $this->callEeoApi();
                    throw new \Exception($msg, $res['errno']);
                }
            }
        } else {
            throw new \Exception($result['error_info']['error'], $result['error_info']['errno']);
        }
    }

    /**
     * 同步课程课节教师学生数据到EEO
     *
     */
    function syncdata(AppointEvent $event)
    {
        try{
            ## 创建课程
            $this->setUri('addCourse');
            $cfile = $this->uploadCheck($event->Filedata);
            $data = $this->dataMaker();
            $data["courseName"] = $event->courseName;
            $data["folderId"] = $event->folderId;
            $data["Filedata"] = $cfile;
            $data["expiryTime"] = $event->expiryTime;
            $this->setRequest($data);
            $result = $this->callEeoApi();
            if($result['error_info']['errno'] === 1) {
                $event->setCourseID($result['data']);
            }else{
                throw new \Exception($result['error_info']['error'], $result['error_info']['errno']);
            }

            ## 添加预约生
            $this->student($event);

            ## 添加旁听生
            $auditors_add = [];
            $auditors= DB::table('schedules_students')
                ->where('scheduleid',$event->chimpCourseId)
                ->where('identity',2)
                ->get();
            foreach ($auditors as $auditor){
                $auditors_add[] = $auditor->studentuid;
            }

            if(is_array($auditors_add)){
                $students = Student::find($auditors_add);
                $event->setIdentity(ClasseStuden::AUDITOR);
                $event->unsetStudents();
                $event->setStudents($students);
                $this->student($event);
            }

            ## 创建课节
            $schedule = Schedule::find($event->chimpCourseId);
            $event->setLesson($schedule, Event::CREATE);

            $schduleEvents = $event->getLessons();
            foreach($schduleEvents as $scheduleEvent) {
                $scheduleEvent->setCourseID($event->courseId);
                $scheduleEvent->classId = 1;
                event($scheduleEvent);
            }
        }catch (\Exception $e){
            throw $e;
        }
    }

}
